from pathlib import Path
import numpy as np
#import cv2
from pydicom.dataset import Dataset
from dcm import read_dcm_by_pydicom, read_dcm_to_8bit, cv_show


def convert_dcm(file:Path, show_flag=False)-> Dataset:
    """
    convert dicom
    :param file: input file
    :param show_flag: show dcm image
    :return:
    """
    if not file.exists():
        return Dataset()
    convert_dcm:Dataset = read_dcm_by_pydicom(str(file))
    convert_dcm.PatientName = ""
    convert_dcm.InstitutionName = ""
    convert_dcm.PatientBirthDate = ""
    if show_flag:
        save_path = 'convert_mm.dcm'
        convert_dcm.save_as(save_path)
        image = read_dcm_to_8bit(save_path)
        # cv_show('image', np.squeeze(image), 0.25)
        # cv2.waitKey(0)
    return convert_dcm


def save_dcm(dcm:Dataset, file:Path):
    return dcm.save_as(str(file))


def convert_mamogram_dcm(file:Path, save_path:Path):
    if not file.exists():
        return False
    dcm = convert_dcm(file)
    save_dcm(dcm, save_path)



def convert_case(in_path:Path, save_path:Path):
    if not in_path.exists():
        return False

    out_path = save_path.joinpath(in_path.name)
    if not out_path.exists():
        out_path.mkdir()

    dcm_files = sorted(in_path.glob("*.dcm"))
    if len(dcm_files) == 0:
        return False

    for file in dcm_files:
        convert_mamogram_dcm(file, out_path.joinpath(file.name))


def test():
    pa = '/home/blake/data/medical/datasets/breast/乳腺癌/001091461200/1241581-王小琴-20190424342445'
    save_pa = '/home/blake/data/medical/datasets/breast/乳腺癌/convert'
    convert_case(Path(pa), Path(save_pa))



test()